import docs from '@/genrate/tutorial.json'
import store from "./store.js";

const getDocCompByKey = async key => {
    const moudle = await import(`./tutorial/${key}`)
    return moudle.default
}

const getDbMode = () => {
    return store.state.dbMode;
}

export const getWelcomeDocComp = async () => {
    const doc = docs.find(doc => doc.type === 'Welcome')
    return await getDocCompByKey(doc.key)
}

export const getMainDocCompByIndex = async index => {
    const doc = getMainDocs().find((m, idx) => idx === index);
    return await getDocCompByKey(doc.key)
}

export const getMainDocTotalNum = () => getMainDocs().length;

export const getMainDocs = () => {
    const groupDocs = docs
        .filter(doc => doc.type === 'Main')
        .reduce((groups, item) => {
            const gk = item.group;
            if(!groups[gk]){
                groups[gk] = [];
            }
            groups[gk].push(item);
            return groups;
        }, {})

    const mode = getDbMode();
    return Object.keys(groupDocs)
        .map(key => {
            const items = groupDocs[key];
            if(items.length === 1){
                return items[0];
            }
            const modeDoc = items.find(item => item.mode === mode);
            if(modeDoc){
                return modeDoc;
            }
            return items.find(item => item.mode === 'All');
        })
        .sort((a, b) => a.index - b.index)
};